package com.freedom.monitor.myeye.commmon.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Base64;

import org.apache.kafka.common.record.KafkaLZ4BlockInputStream;
import org.apache.kafka.common.record.KafkaLZ4BlockOutputStream;

public class CompressUtils {
	public static int KAFKA_LZ4 = 0;

	/**
	 * 压缩
	 * 
	 * @param data
	 * @return
	 * @throws IOException
	 */
	public static String compress(String data) {
		PrintWriter out = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			out = new PrintWriter(new KafkaLZ4BlockOutputStream(baos, 4));
			out.print(data);
			out.flush();
			return Base64.getEncoder().encodeToString(baos.toByteArray());
		} catch (Exception e) {
			return null;// 出现了异常
		} finally {
			if (out != null) {
				out.close();
			}
		}

	}

	/**
	 * 解压缩
	 * 
	 * @param data
	 * @return
	 * @throws IOException
	 */
	public static String deCompress(String data) {
		BufferedReader br = null;
		try {
			byte[] source = Base64.getDecoder().decode(data);
			ByteArrayInputStream bais = new ByteArrayInputStream(source);
			br = new BufferedReader(new InputStreamReader(new KafkaLZ4BlockInputStream(bais)));
			StringBuffer sb = new StringBuffer();
			String str = null;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}
			return sb.toString();
		} catch (Exception e) {
			return null;
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}

	}
}